<?php

/**
 * Server_Api_Collect
 * 评论服务
 * Author: netman
 * DateTime:  2023/9/11 16:37
 */
class Service_Api_Comment extends Contract_Api_Comment
{

    use Trait_Api_Common;
    use Trait_Api_Image;
    use Trait_Api_Comment;
    use Trait_Api_Model;
    use Trait_Api_Response;

    public function __construct()
    {

    }

    /**
     * 评论列表
     * @param $typeid
     * @param $product_id
     * @param $flag
     * @param $page
     * @param $pagesize
     * @return array
     * User: netman
     * Date: 2023/9/18 15:25
     */
    function list($type_id, $product_id, $flag, $page, $pagesize): array
    {
        $builder = DB::select()->from('comment')
            ->where('isshow', '=', 1)
            ->and_where('typeid', '=', $type_id)
            ->and_where('articleid', '=', $product_id)
            ->and_where(DB::expr(" AND (dockid=0 OR dockid='' OR dockid IS NULL) "));
        if ($flag == 'pic') {
            $builder->and_where(DB::expr(" AND LENGTH(TRIM(piclist))>0"));
        } elseif ($flag == 'well') {
            $builder->and_where('level', 'in', [4, 5]);
        } elseif ($flag == 'mid') {
            $builder->and_where('level', 'in', [2, 3]);
        } elseif ($flag == 'bad') {
            $builder->and_where('level', '=', 1);
        }
        $total  = $builder->execute()->count();
        $offset = ($page - 1) * $pagesize;
        $arr    = $builder->offset($offset)->limit($pagesize)->order_by('id', 'desc')->execute()->as_array();
        $out    = array();

        foreach ($arr as &$r) {
            $r           = self::handle_comment_data($r);
            $sub_comment = DB::select()->from('comment')
                ->where('dockid', '=', $r['id'])
                ->and_where('isshow', '=', 1)
                ->execute()->as_array();
            foreach ($sub_comment as &$sub) {
                $sub = self::handle_comment_data($sub);
            }
            $r['sub_comment'] = $sub_comment;

            $out[] = $r;
        }
        return array(
            'total' => $total,
            'list'  => $out
        );
    }

    public function handle_comment_data($r)
    {
        $need_fields = array(
            'id', 'typeid', 'orderid', 'articleid', 'memberid', 'pid', 'content', 'addtime', 'level', 'piclist', 'jifentprice',
            'jifencomment', 'jifenbook', 'nickname', 'litpic', 'pltime', 'percent', 'level_num', 'picthumb', 'reply'
        );

        if (!empty($r['memberid'])) {
            $awardinfo         = Model_Member_Order::get_award_info($r['orderid']);
            $memberinfo        = Model_Member::get_member_info($r['memberid']);
            $r['jifentprice']  = $awardinfo['jifentprice'];
            $r['jifencomment'] = $awardinfo['jifencomment'];
            $r['jifenbook']    = $awardinfo['jifenbook'];
            $r['nickname']     = empty($memberinfo['nickname']) ? '匿名' : St_Functions::cutstr_html($memberinfo['nickname'], 9);
            $r['litpic']       = !empty($memberinfo['litpic']) ? $memberinfo['litpic'] : Model_Member::member_nopic();
        } else {
            $r['jifencomment'] = $r['vr_jifencomment'];
            $r['nickname']     = $r['vr_nickname'] ?? '匿名';
            $r['litpic']       = $r['vr_headpic'] ?? Model_Member::member_nopic();
        }

        $r['litpic'] = Model_Api_V2_Common::get_member_header_pic($r['litpic']);

        // 评论随机时间(秒之前)
        $r['pltime']    = $this->random_pl_time();
        $r['percent']   = 20 * $r['level'] . '%';
        $r['level_num'] = $r['level'];
        $r['level']     = Model_Member::member_rank($r['memberid'], ['return'   => 'current', 'vr_grade' => $r['vr_grade']]);
        $r['addtime']   = date("Y-m-d", $r['addtime']);

        // 图片列表
        if (!empty($r["piclist"])) {
            $r['piclist'] = explode(',', $r['piclist']);
            $picthumb     = [];

            foreach ($r['piclist'] as &$pic) {
                $pic_img_arr = explode('||', $pic);
                $pic         = $this->img_url($pic_img_arr[0]);
                $picthumb[]  = $this->img_url($pic_img_arr[0], 86, 86);
            }

            $r["picthumb"] = $picthumb;
        }
        $this->filter_data($need_fields, $r);

        return $r;
    }

    /**
     * 统计信息
     * @param $product_id
     * @param $typeid
     * @return array|mixed
     * User: netman
     * Date: 2023/9/18 17:30
     */
    function stats_info($product_id, $typeid)
    {
        $table = $this->get_main_table($typeid);
        $score = DB::select('satisfyscore')->from($table)->where('id','=',$product_id)->execute()->get('satisfyscore');
        $count = $this->get_comment_count($typeid, $product_id, $score);
        return $count;
    }

    function add_order_comment(array $params)
    {
        $type_id = (int)$params['type_id'];
        $product_id = (int)$params['product_id'];
        $order_id = (int)$params['order_id'];
        $level = (int)$params['level'];
        $content = $params['content'];
        $piclist = $params['piclist'];
        //通过订单号码检测是否id是否合法
        $row = DB::select()->from('member_order')
            ->where('id', '=', $order_id)
            ->and_where('memberid', '=', $params['mid'])
            ->and_where('ispinlun', '=', 0)
            ->execute()
            ->current();
        if (empty($row)) {
            throw new Exception("找不到订单或者订单已评论");

        }

        $arr = array();
        $arr['memberid'] = $params['mid'];
        $arr['content'] = $content;
        $arr['orderid'] = $order_id;
        $arr['articleid'] = $product_id;
        $arr['level'] = $level;
        $arr['typeid'] = $type_id;
        $arr['addtime'] = time();
        $arr['piclist'] = $piclist;
        $model = ORM::factory('comment');
        foreach ($arr as $key => $value) {
            $model->$key = $value;
        }
        $model->save();
        $flag = 0;
        if ($model->saved()) {
            // 订单创建完成事件
            Hook::trigger('order_comment', $row);
            $flag = 1;
        }
        return $flag;
    }

    function add_article_comment(array $params)
    {
        $article_id = (int)$params['article_id'];
        $type_id = (int)$params['type_id'];
        $reply_id = (int)$params['reply_id'];
        $captcha_key = $params['captcha_key']; // 图片验证码key
        $checkcode = $params['checkcode'];//验证码
        $is_anonymous = $params['is_anonymous'];
        $content = $params['content'];

        //验证码验证
        if ( ! Model_Api_V2_Common::verify_image_code($captcha_key, $checkcode)) {
            throw new Exception('验证码错误');

        }
        $arr = array();
        $arr['typeid'] = $type_id;
        $arr['articleid'] = $article_id;
        $arr['content'] = $content;
        $arr['addtime'] = time();
        //是否匿名
        if ($is_anonymous == 'yes') {
            $arr['memberid'] = 0;
        } else {
            $arr['memberid'] = $params['mid'];
        }
        $need_confirm = 1;
        //攻略是否开启审核
        $adult_open = Model_Sysconfig::get_configs(0, 'cfg_article_pinlun_audit_open', true);
        if ($adult_open == 0 && $type_id == 4) {
            $arr['isshow'] = 1;
            $need_confirm = 0;
        }
        //游记是否开启审核
        $note_adult_open = Model_Sysconfig::get_configs(0, 'cfg_notes_pinlun_audit_open', true);
        if ($note_adult_open == 0 && $type_id == 101) {
            $arr['isshow'] = 1;
            $need_confirm = 0;
        }

        $arr['dockid'] = $reply_id ? $reply_id : 0;
        $flag = DB::insert('comment', array_keys($arr))->values(array_values($arr))->execute();
        if ($arr['isshow'] == 1) {
            Model_Comment::on_verified($flag[0], $type_id, $arr['memberid']);
        }
        if ($flag) {

            return array('need_confirm' => $need_confirm);
        } else {
            return [];
        }

    }


}